﻿using System;
using System.Collections.Generic;
using System.Linq;
using HighDiveEngine.Model;

namespace HighDiveEngine.Aggregates
{
    /// <summary>
    /// List holding dives, used for queue and history).
    /// </summary>
    public class DiveList : List<Dive>
    {
        /// <summary>
        /// Return a new DiveList that is a copy of the current list bu sorted after a divers total result.
        /// </summary>
        /// <returns>DiveList sorted by result</returns>
        public DiveList GetResultList()
        {
            var dict = new Dictionary<Diver, double?>();
            foreach (var dive in this)
            {
                if (dive.TotalScore == null)
                    dive.CalculateTotalScore();

                if (dict.ContainsKey(dive.Diver))
                    dict[dive.Diver] += dive.TotalScore;
                else
                    dict[dive.Diver] = dive.TotalScore;
            }

            var resultList = new DiveList();
            //d.AddRange(this);
            //Clear();

            while (dict.Count > 0)
            {
                var diver = dict.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
                dict.Remove(diver);
                var li = from dives in this where dives.Diver == diver orderby dives.Date select dives;
                resultList.AddRange(li);
            }

            return resultList;
        }

        public void GenerateStartOrder()
        {
            var numDivers = this.Select(x => x.Diver).Distinct().Count();
            var sortedList = this.OrderBy(x => (x.Diver.StartNumber + (x.DiveNumber * numDivers))).ToList();
            for (int i = 0; i < sortedList.Count; i++)
            {
                sortedList[i].QueueOrderNumber = i + 1;
            }
        }
    }
}
